// 调试信息
console.log('AuthManager loaded:', typeof AuthManager);
console.log('authManager loaded:', typeof authManager);

document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const loginBtn = document.getElementById('loginBtn');
    const loading = document.getElementById('loading');
    const loginText = document.getElementById('loginText');
    const alertContainer = document.getElementById('alert-container');

    // 显示提示信息
    function showAlert(message, type = 'danger') {
        alertContainer.innerHTML = `
            <div class="alert alert-${type}">
                ${message}
            </div>
        `;
    }

    // 显示加载状态
    function setLoading(loading) {
        if (loading) {
            loginBtn.disabled = true;
            document.getElementById('loading').classList.add('show');
            loginText.style.display = 'none';
        } else {
            loginBtn.disabled = false;
            document.getElementById('loading').classList.remove('show');
            loginText.style.display = 'inline';
        }
    }

    // 处理登录
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;

        if (!username || !password) {
            showAlert('请输入用户名和密码');
            return;
        }

        setLoading(true);
        alertContainer.innerHTML = '';

        try {
            const result = await AuthManager.login(username, password);
            
            if (result.success) {
                showAlert('登录成功，正在跳转...', 'success');
                setTimeout(() => {
                    window.location.href = '/ercms/dashboard';
                }, 1000);
            } else {
                showAlert(result.message || '登录失败');
            }
        } catch (error) {
            console.error('登录错误:', error);
            showAlert(error.message || '登录失败，请重试');
        } finally {
            setLoading(false);
        }
    });

    // 检查URL参数中的错误信息
    const urlParams = new URLSearchParams(window.location.search);
    const error = urlParams.get('error');
    const message = urlParams.get('message');
    const logout = urlParams.get('logout');

    if (error) {
        showAlert('登录失败，请检查用户名和密码！');
    } else if (message) {
        showAlert(message, 'success');
    } else if (logout) {
        showAlert('您已成功退出系统', 'success');
    }
}); 